package com.coolham.switter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.coolham.common.util.DateTimeUtil;
import com.coolham.switter.util.WeiboUtil;

import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class WeiboItemsActivity extends Activity {
	final static String TAG = "WeiboItemsActivity";

	private Context mContext;
	private List<Status> mWeiboItem = new ArrayList<Status>();

	private ListView mListView;
	private ProgressBar mProgressBar;

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.v(TAG, ">>> BroadcastReceiver onReceive=" + action);

			Bundle bundle = intent.getExtras();

			if (action.equals(Global.ACTION_MAIN_RELOAD)) {
				int tab_id = bundle.getInt("tab_id");
				if (tab_id == 0) {
					Message message = new Message();
					message.setData(bundle);
					message.what = 1;
					mHandler.sendMessage(message);
				}
			} else {
				Log.w(TAG, "Unknown broadcast message:" + action);
			}
		}
	};

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG, ">>>handleMessage:" + msg.toString());

			Bundle data = null;
			String receiverIntent = null;
			Intent intent = null;

			switch (msg.what) {
			case 1:
				RequestTask task = new RequestTask();
				task.execute();
				break;
			default:
				break;
			}
		}

	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.weibo_items_view);

		mListView = (ListView) findViewById(R.id.weibo_items_list);
		initListView();

		// adView.setRequestInterval(60);
		mProgressBar = (ProgressBar) this
				.findViewById(R.id.weibo_itmes_progress_bar);
		Drawable d = this.getResources().getDrawable(
				R.drawable.custom_progressbar);
		mProgressBar.setProgressDrawable(d);
		mProgressBar.setProgress(50);
		mProgressBar.setIndeterminate(true);

		// broadcast message
		IntentFilter filter = new IntentFilter();
		filter.addAction(Global.ACTION_MAIN_RELOAD);
		registerReceiver(mBroadcastReceiver, filter);

		//
		//RequestTask task = new RequestTask();
		//task.execute();

	}

	private void initListView() {

		MyAdapter adapter = new MyAdapter(this);

		mListView.setAdapter(adapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				showDetailedWeibo(position);
			}

		});

		mListView
				.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

					public void onCreateContextMenu(ContextMenu menu,
							View arg1, ContextMenuInfo arg2) {
						menu.setHeaderTitle("Situstion Options");
						// menu.add(0, OPT_EDIT_SITUATION, 1, "Edit Situation");
						// menu.add(0, OPT_DELETE_SITUATION, 2,
						// "Delete Situation");

					}
				});
	}

	private final class ViewHolder {
		public ImageView iconView;
		public TextView titleView;
		public TextView timeView;
		public TextView textView;
		public TextView sourceView;
	}

	/**
	 * My List View Adapter
	 * 
	 * @author Jeff
	 * 
	 */
	private class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return mWeiboItem.size();
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater
						.inflate(R.layout.weibo_items_list, null);
				holder.iconView = (ImageView) convertView
						.findViewById(R.id.wb_items_list_icon);
				holder.titleView = (TextView) convertView
						.findViewById(R.id.wb_items_list_title);
				holder.timeView = (TextView) convertView
						.findViewById(R.id.wb_items_list_time);
				holder.textView = (TextView) convertView
						.findViewById(R.id.wb_items_list_text);
				holder.sourceView = (TextView) convertView
						.findViewById(R.id.wb_items_list_source);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Status status = mWeiboItem.get(position);
			Date postDate = status.getCreatedAt();
			String source = status.getSource();

			holder.iconView.setBackgroundResource(R.drawable.logo);
			holder.titleView.setText(status.getUser().getScreenName());
			holder.timeView.setText(DateTimeUtil.autoTimeFormat(postDate));
			holder.textView.setText(status.getText());
			holder.sourceView.setText(WeiboUtil.parseComefrom(source));

			// set situation enable or disable
			holder.iconView.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					View pv = (View) v.getParent();
					int position = mListView.indexOfChild((View) v.getParent());

					// HashMap<String, Object> map = mListItem.get(position);
				}

			});
			/*
			convertView.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					int position = mListView.indexOfChild(v);

					
				}

			});
			*/
			return convertView;
		}

	}

	private class RequestTask extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			mProgressBar.setVisibility(View.VISIBLE);
			// mProgressBar.setProgress(0);
		}

		@Override
		protected String doInBackground(String... params) {
			Log.d(TAG, ">>>DownloadTask:doInBackground");

			Weibo weibo = OAuthConstant.getInstance().getWeibo();

			weibo.setToken(OAuthConstant.getInstance().getToken(),
					OAuthConstant.getInstance().getTokenSecret());

			try {
				mWeiboItem = weibo.getUserTimeline();

				StringBuilder stringBuilder = new StringBuilder("1");
				for (weibo4andriod.Status status : mWeiboItem) {
					stringBuilder.append(status.getUser().getScreenName()
							+ "˵:" + status.getText() + "\n");

				}
			} catch (WeiboException e) {
				e.printStackTrace();
			}
			return null;

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			Log.d(TAG, ">>>DownloadTask:onPostExecute");
			mProgressBar.setVisibility(View.GONE);
			updateListView();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// Log.d(TAG, ">>>DownloadTask:onProgressUpdate:" + values[0]);
			// setProgress(values[0]);
		}
	}

	protected void updateListView() {
		MyAdapter adapter = (MyAdapter) mListView.getAdapter();
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.v(TAG, ">>>onSaveInstanceState");
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.v(TAG, ">>>onRestoreInstanceState");
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	public void exit() {
		Log.v(TAG, ">>>exit?");

		new AlertDialog.Builder(mContext)
				.setTitle(getString(R.string.app_name))
				.setIcon(R.drawable.icon)
				.setMessage(R.string.app_exit_hint)
				.setPositiveButton(getString(R.string.menu_confirm),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// android.os.Process.killProcess(android.os.Process.myPid());
								finish();
							}

						})
				.setNegativeButton(getString(R.string.menu_cancel),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}

						}).show();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null && data.getBooleanExtra("aa", false)) {
			// add your code here to continue with application loading
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void showDetailedWeibo(int pos) {
		Log.v(TAG, ">>>showDetailedWeibo, pos=" + pos);

		Intent intent = new Intent();
		intent.setClass(mContext, DetailWeiboActivity.class);

		Status status = mWeiboItem.get(pos);

		Bundle bundle = new Bundle();
		bundle.putSerializable("status", status);
		intent.putExtras(bundle);

		startActivity(intent);

	}

}
